package com.hubei.Control;

//控制层，响应用户的请求

import com.hubei.Service.UserService;
import com.hubei.vo.Users;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 宋子贤
 * @date 2025/6/24-10:52
 */
@WebServlet("/login.action")
public class LoginControl extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            request.setCharacterEncoding("UTF-8");
            String username = request.getParameter("username").trim();
            String password = request.getParameter("password").trim();

            // 基本输入验证
            if (username == null || username.isEmpty() || password == null || password.isEmpty()) {
                request.setAttribute("loginErr", "用户名或密码不能为空！");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
                return;
            }

            UserService service = UserService.getInstance();
            Users users = new Users();
            users.setUsername(username);
            users.setPassword(password);

            users = service.userLogin(users);

            if (users == null) {
                request.setAttribute("loginErr", "用户名或密码不正确！");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            } else {
                HttpSession session = request.getSession();
                session.setAttribute("userInfo", users);

                // 调试日志：检查 session 和 userInfo
                System.out.println("Session: " + session);
                System.out.println("UserInfo: " + users);

                request.getRequestDispatcher("/main.jsp").forward(request, response);
            }
        } catch (Exception e) {
            // 异常处理：记录日志并显示错误信息
            e.printStackTrace();
            request.setAttribute("loginErr", "系统错误，请稍后再试！");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
